# views.py
# -*- coding: utf-8 -*-
import os
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from django.template import Template
from django.utils._os import safe_join


def get_page_or_404(name):
    '''
    Returns page content as a Django template or raise 404 error.
    :param name:
    :return:
    '''
    try:
        file_path = safe_join(settings.SITE_PAGES_DIRECTORY, name)
    except ValueError:
        if not os.path.exists(file_path):
            raise Http404('Page not found')
    with open(file_path, 'r') as f:
        page = Template(f.read())
    return page


def page(request, slug='page1'):
    '''Render the requested page if found.'''
    file_name = '{}.htm'.format(slug)
    context = {
        'slug': slug,
        'page': get_page_or_404(file_name),
    }
    return render(request, 'index.htm', context)
